package org.codeart.juc.queue;

import lombok.Data;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueDemo {

    // 自定义的任务类
    @Data
    public static class ITask implements Delayed {

        // 任务名称
        private final String name;

        // 什么时间点执行 单位 ms
        private final Long time;

        public ITask(String name, Long time) {
            this.name = name;
            this.time = System.currentTimeMillis() + time;
        }

        /**
         * 设置任务什么时候可以出任务队列
         *
         * @param unit the time unit
         * @return
         */
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(time - System.currentTimeMillis(), TimeUnit.NANOSECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            ITask task = (ITask) o;
            return (int) (this.time - task.getTime());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // DelayQueue 中的元素需要实现 Delayed 接口
        DelayQueue<ITask> queue = new DelayQueue<>();
        ITask t1 = new ITask("A", 1000L);
        ITask t2 = new ITask("B", 5000L);
        ITask t3 = new ITask("C", 3000L);
        ITask t4 = new ITask("D", 2000L);
        queue.add(t1);
        queue.add(t2);
        queue.add(t3);
        queue.add(t4);
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
    }

}
